<template>
  <div class="table-container">
    <el-form :inline="true" :model="formInline" class="form-inline">
      <el-form-item label="题目名称">
        <el-input v-model="formInline.user" placeholder="请输入题目名称" @input="onSubmit"></el-input>
      </el-form-item>
      <el-form-item label="题目分类">
        <el-select v-model="formInline.region" class="m-2" placeholder="Select" size="large" @change="onSubmit" clearable>
          <!-- <el-option v-for="item in options" :key="item.name" label="全部" :value="item.id" /> -->
          <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.id" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="tj">添加</el-button>
      </el-form-item>
    </el-form>
    <el-table ref="filterTableRef" class="table-list" row-key="date" :data="tableData" style="width: 100%">
      <el-table-column prop="title" label="题目名称" width="400"> </el-table-column>
      <el-table-column prop="catename" label="题目分类" width="200"> </el-table-column>
      <el-table-column label="已发布" width="200">
        <template #default="scope">
          <el-switch v-model="scope.row.ifopen" class="ml-2" active-color="#13ce66" inactive-color="#ff4949" @change="fb(scope.row)" />
        </template>
      </el-table-column>

      <el-table-column label="添加时间" width="200">
        <template #default="scope">
          <span>
            {{ dateFliter(scope.row.created_time) }}
          </span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作">
        <template #default="scope">
          <el-button size="mini" type="primary" @click="handleEdit(scope.$index, scope.row)">详情</el-button>
          <el-button size="mini" type="warning" @click="put(scope.$index, scope.row)">修改</el-button>
          <el-popconfirm confirm-button-text="确定" cancel-button-text="取消" icon="el-icon-info" icon-color="red" title="确定删除该条记录吗？" @confirm="handleDelete(scope.$index, scope.row)">
            <template #reference>
              <el-button size="mini" type="danger">删除</el-button>
            </template>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      :hide-on-single-page="false"
      :current-page="currentPage"
      :page-sizes="[5, 10, 15, 20, 25]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    >
    </el-pagination>
    <!-- 详情 -->
    <el-dialog v-model="dialogVisible" title="详情" width="30%" :before-close="handleClose">
      <!-- {{zs}} -->
      <el-row :gutter="20">
        <el-col :span="4" style="text-align: right; align-items: center"> 分类: </el-col>
        <el-col :span="18" style="text-align: left; align-items: center">
          {{ zs.catename }}
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4" style="text-align: right; align-items: center"> 题目名称: </el-col>
        <el-col :span="18" style="text-align: left; align-items: center">
          {{ zs.title }}
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="4" style="text-align: right"> 答案: </el-col>
        <el-col :span="18" style="text-align: left">
          <!-- {{zs.answer}} -->
          <div v-html="zs.answer"></div>
        </el-col>
      </el-row>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 修改数据 -->
    <el-dialog v-model="dialogVisibles" title="修改" width="50%" :before-close="handleCloses">
      <el-form
        ref="ruleFormRef"
        :model="form1"
        status-icon
        :rules="rules"
      >
          <el-form-item label="题目名称:" prop="name">
            <el-input v-model="form1.name" />
          </el-form-item>
          <el-form-item label="分类" prop="value">
            <el-select v-model="form1.value" class="m-2" placeholder="Select" size="large">
                  <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
          <el-form-item label="答案" prop="richHtml">
            <RichEditor :model-value="form1.richHtml" @update:modelValue="handleUpdateValue"></RichEditor>
          </el-form-item>
          <el-form-item>
              <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="qd">确定</el-button>
          </el-form-item>
      </el-form>

    </el-dialog>
    <!-- 添加用户 -->
    <el-dialog v-model="dialogVisiblets" title="添加" width="50%" :before-close="handleClose">
        <el-form
        ref="ruleFormRef"
        :model="form"
        status-icon
        :rules="rules"
      >
          <el-form-item label="题目名称:" prop="name">
            <el-input v-model="form.name" />
          </el-form-item>
          <el-form-item label="分类" prop="value">
            <el-select v-model="form.value" class="m-2" placeholder="Select" size="large">
                  <el-option v-for="item in options" :key="item.name" :label="item.name" :value="item.id" />
                </el-select>
          </el-form-item>
          <el-form-item label="答案" prop="richHtml">
            <RichEditor :model-value="form.richHtml" @update:modelValue="handleUpdateValue"></RichEditor>
          </el-form-item>
          <el-form-item>
              <el-button @click="qxx(ruleFormRef)">取消</el-button>
                <el-button type="primary" @click="tjqd(ruleFormRef)">确定</el-button>
          </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import { defineComponent, onMounted, reactive, ref,toRefs } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import permission from '@/directive/permission'
import Service from './api/index'
import { ElMessage } from 'element-plus'
import type { FormInstance } from 'element-plus'
export default defineComponent({
  name: 'TableList',
  directives: {
    permission
  },
  setup() {
    const ruleFormRef = ref<FormInstance>()
    const router = useRouter()
    const filterTableRef = ref()
    const dialogVisible = ref(false)
    const dialogVisibles = ref(false)
    const dialogVisiblets = ref(false)
    const datavalue = ref()
    const obj = reactive({
      form: {
        value: '',
        name: '',
        richHtml: ''
      },
      form1: {
        id: '',
        value: '',
        name: '',
        richHtml: ''
      }
    })
    const options = ref([])
    const obj1 = reactive({
      datas: {},
      datalist: []
    })
    const state = reactive({
      tableData: [],
      tableDatalist: [],
      currentPage: 1,
      pageSize: 5,
      search: ''
    })
    const datas = async () => {
      const res = await Service.question_datas()
      const res1 = await Service.cate_datas()
      console.log(res1.data)

      options.value = res1.data
      //   console.log(res.data)
      total.value = res.data.length
      // state.tableData = res.data
      state.tableDatalist = res.data
      let start = (state.currentPage - 1) * state.pageSize
      let end = start + state.pageSize
      state.tableData = res.data.slice(start, end)
    }
    datas()
    const formInline = reactive({
      user: '',
      region: ''
    })
    const total = ref()

    const dateFliter = (val: any, format = 'YYYY-MM-DD hh:mm:ss') => {
      if (!isNaN(val)) {
        val = parseInt(val)
      }
      return dayjs(val).format(format)
    }

    onMounted(() => {
      // eslint-disable-next-line no-console
      console.dir(filterTableRef.value)
    })
    let zs = ref({})
    const handleEdit = async (index: any, row: any) => {
      console.log(row)
      zs.value = row
      dialogVisible.value = true
    }
    const put = async (index: any, row: any) => {
      console.log(index, row)
      console.log(row.cateid)
      obj.form1.id = row.id
      obj.form1.name = row.title
      obj.form1.value = row.cateid_id
      obj.form1.richHtml = row.answer
      dialogVisibles.value = true
    }
    const qd = async () => {
      dialogVisibles.value = false
      console.log(obj.form1.richHtml)

      const res = await Service.question_put({ id: obj.form1.id, cateid: obj.form1.value, title: obj.form1.name, answer: obj.form1.richHtml })
      console.log(res)
      if (res.code == '200') {
        ElMessage({
          message: '修改用户成功',
          type: 'success'
        })
      }
      datas()
    }

    const handleDelete = async (index: any, row: any) => {
      // eslint-disable-next-line no-console
      // console.log(index, row)
      console.log(row.id)
      const res = await Service.question_del(row.id)
      if (res.code == '200') {
        ElMessage({
          message: '删除用户成功',
          type: 'success'
        })
      }
      datas()
    }
    const handleSizeChange = (val: any) => {
      // eslint-disable-next-line no-console
      console.log(`每页 ${val} 条`)
      state.pageSize = val
      // request api to change tableData
      let start = (state.currentPage - 1) * state.pageSize
      let end = start + state.pageSize
      state.tableData = state.tableDatalist.slice(start, end)
    }
    const handleCurrentChange = (val: any) => {
      // eslint-disable-next-line no-consoletter
      console.log(`当前页: ${val}`)
      state.currentPage = val
      // request api to change tableData
      let start = (state.currentPage - 1) * state.pageSize
      let end = start + state.pageSize
      state.tableData = state.tableDatalist.slice(start, end)
    }

    const onSubmit = async () => {
      if (formInline.region && formInline.user) {
        const row = await Service.question_lh({ title: formInline.user, cart: formInline.region })
        // console.log(row.data);
        state.tableData = row.data
        state.tableDatalist = row.data
      } else if (formInline.user && !formInline.region) {
        const row = await Service.question_ss(formInline.user)
        state.tableData = row.data
      } else if (!formInline.user && formInline.region) {
        console.log(formInline.region)

        const row = await Service.question_datas1({ id: formInline.region })
        state.tableData = row.data
      } else {
        datas()
      }
    }

    const tj = () => {
      dialogVisiblets.value = true
    }
    const validatePass = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('题目名称不能为空'))
      } else {
        callback()
      }
    }
    const validatePass2 = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('分类不能为空'))
      } else {
        callback()
      }
    }
    const validatePass3 = (rule: any, value: any, callback: any) => {
      if (value === '') {
        callback(new Error('答案不能为空'))
      } else {
        callback()
      }
    }
    const rules = reactive({
      name: [{ validator: validatePass, trigger: 'blur' }],
      value: [{ validator: validatePass2, trigger: 'blur' }],
      richHtml: [{ validator: validatePass3, trigger: 'blur' }],
    })
    const tjqd =  (formEl: FormInstance | undefined) => {
      if (!formEl) return
        formEl.validate(async(valid) => {
          if (valid) {
             const res = await Service.question_create({ cateid: obj.form.value, title: obj.form.name, answer: obj.form.richHtml })
            console.log(res)
            if (res.code == '200') {
              ElMessage({
                message: '添加用户成功',
                type: 'success'
              })
            }

            dialogVisiblets.value = false
            datas()
            formEl.resetFields()
            obj.form.richHtml==''
          } else {
            console.log('error submit!')
            return false
          }
        })
    }
    const handleUpdateValue = (val: any) => {
      obj.form.richHtml = val
      obj.form1.richHtml = val
    }
    const fb = async (row: any) => {
      let obj = await Service.question_put({ id: row.id, ifopen: row.ifopen })
      console.log(obj)
      if (obj.code == '200') {
        ElMessage({
          message: '发布修改成功',
          type: 'success'
        })
      }
    }
    const qxx = (formEl: FormInstance | undefined) => {
      if (!formEl) return
      formEl.resetFields()
      obj.form.richHtml==''
      dialogVisiblets.value = false
    }
    return {
      formInline,
      total,
      ...toRefs(state),
      ...toRefs(obj),
      ...toRefs(obj1),
      handleCurrentChange,
      handleSizeChange,
      onSubmit,
      handleEdit,
      handleDelete,
      filterTableRef,
      dialogVisible,
      put,
      dialogVisibles,
      qd,
      tj,
      dialogVisiblets,
      tjqd,
      datavalue,
      dateFliter,
      options,
      handleUpdateValue,
      zs,
      fb,
      ruleFormRef,
      rules,
      qxx
    }
  }
})
</script>
<style lang="stylus" scoped>
.table-container {
  .form-inline {
    margin: 15px;
    text-align: left;
  }

  .table-list {
    margin: 15px;
  }
}

.el-row {
  margin-bottom: 20px;
}

.el-row:last-child {
  margin-bottom: 0;
}

.el-col {
  border-radius: 4px;
}

.grid-content {
  border-radius: 4px;
  min-height: 36px;
}
</style>
